package com.ywgt.system.service.impl;

import com.ywgt.entity.FastDFSFile;
import com.ywgt.system.mapper.UserMapper;
import com.ywgt.system.service.FileService;
import com.ywgt.utils.FastDFSUtil;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public String upload(MultipartFile file) {
        String s = UUID.randomUUID().toString().replaceAll("-", "");
        String date = DateTime.now().toString("yyyy-MM-dd");
        FastDFSFile fastDFSFile=null;
        String url=null;
        try {
            fastDFSFile=new FastDFSFile(s+date,file.getBytes(), StringUtils.getFilenameExtension(file.getOriginalFilename()));
            url = FastDFSUtil.fileUpload(fastDFSFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return url;
    }

    @Override
    public void delete(String path) {
        //http://172.20.10.5:8080/group1/M00/00/00/rBQKBWACfzaAO-9hAACc-_xa8_M742.jpg
        String[] split = path.split("/");
        int length = split[3].length();
        String groupName=split[3];
        String filePath = path.substring(path.lastIndexOf(split[3]) + length+1);
        try {
            FastDFSUtil.deleteFile(groupName,filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
